﻿using System;
using System.Windows;
using System.Windows.Controls;


namespace WindowsPhone7UXGuide {

	public class MiniWrapPanel : Panel {

		protected override Size MeasureOverride(Size availableSize) {
			double maxRowHeight = 0;
			double maxColumWidth = 0;

			Point currentPosition = new Point();

			Size availableChildSize = availableSize;

			foreach (FrameworkElement child in this.Children) {

				child.Measure(availableChildSize);

				Size desiredSize = child.DesiredSize;

				if (desiredSize.Width + currentPosition.X > availableSize.Width && currentPosition.X != 0) {

					currentPosition.Y += maxRowHeight;

					maxColumWidth = Math.Max(maxColumWidth, currentPosition.X);

					currentPosition.X = desiredSize.Width;
					maxRowHeight = desiredSize.Height;
				}
				else {
					currentPosition.X += desiredSize.Width;
					maxRowHeight = Math.Max(maxRowHeight, desiredSize.Height);
				}
			}

			maxColumWidth = Math.Max(maxColumWidth, currentPosition.X);

			return new Size(maxColumWidth, currentPosition.Y + maxRowHeight);
		}

		protected override Size ArrangeOverride(Size finalSize) {

			double maxRowHeight = 0;
			Point currentPosition = new Point();

			foreach (FrameworkElement child in this.Children) {


				Size desiredSize = child.DesiredSize;
				if (desiredSize.Width + currentPosition.X > finalSize.Width && currentPosition.X != 0) {

					currentPosition.X = 0;
					currentPosition.Y += maxRowHeight;


					child.Arrange(new Rect(currentPosition.X, currentPosition.Y, desiredSize.Width, desiredSize.Height));

					currentPosition.X += desiredSize.Width;
					maxRowHeight = desiredSize.Height;
				}
				else {
					child.Arrange(new Rect(currentPosition.X, currentPosition.Y, desiredSize.Width, desiredSize.Height));

					currentPosition.X += desiredSize.Width;
					maxRowHeight = Math.Max(maxRowHeight, desiredSize.Height);
				}
			}

			return finalSize;
		}
	}
}
